package com.example.calendarapp;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;


/**
 * The Class DayFragmentAdapter.
 * Used by DayFragment for the custom Listview view
 */

public class DayFragmentAdapter extends BaseAdapter
{
	private Context context;
	private EventsDataSource data;
	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	private String[] hours = {"12AM", "1AM", "2AM", "3AM", "4AM", "5AM", "6AM", "7AM", "8AM",
				"9AM", "10AM", "11AM", "12PM", "1PM", "2PM", "3PM", "4PM", "5PM",
				 "6PM", "7PM", "8PM", "9PM", "10PM", "11PM"};
	private Event[] events = new Event[24];
	private Calendar c;
	
	/**
	 * Constructor, sets up calendar and gets the singleton data source object
	 * @param context
	 */
	
	public DayFragmentAdapter(Context ctx)
	{
		c = Calendar.getInstance();
		context = ctx;
		data = EventsDataSource.getInstance(ctx);
	}
	
	/**
	 * Get count returns number of items in list, one for each hour in day (24)
	 * 
	 * @return 24
	 */
	
	@Override
	public int getCount()
	{
		return 24;
	}
	
	/**
	 * getItem returns the event item at position i in list
	 * @param i
	 * @return i'th event in list
	 */
	
	@Override
	public Event getItem(int i)
	{
		return events[i];
	}
	
	@Override
	public long getItemId(int i)
	{
		return i;
	}
	/**
	 * View inflater method, uses the dataSource object to get hour event then sets the view data from the event data
	 * 
	 * @param position
	 * @param view childview
	 * @param viewgroup parentview
	 * 
	 * @return view inflatedview
	 */
	public View getView(int arg0, View arg1, ViewGroup arg2)
	{
		LayoutInflater inflater = LayoutInflater.from(context);
		View convertView = inflater.inflate(R.layout.dayitem, null);

			Event e = data.getHourEvent(arg0, df.format(c.getTime()), c.get(Calendar.DAY_OF_WEEK)-1);
			TextView name = (TextView) convertView.findViewById(R.id.dayItemName);
			if(e == null)
				name.setText(" ");
			else
			{
				name.setText(e.getName());
				name.setTextColor(Resources.getSystem().getColor(e.getColor()));
				events[arg0] = e;
				
			}
			TextView hour = (TextView) convertView.findViewById(R.id.dayItemHour);
			hour.setText(hours[arg0]);
		return convertView;
	}
	
	/**
	 * increment the calendar, used by the swipe detector
	 */
	
	public void incrementDay()
	{
		c.add(Calendar.DATE, 1);
	}
	
	/**
	 * decrement the calendar, used by the swipe detecor
	 */
	
	
	public void decrementDay()
	{
		c.add(Calendar.DATE, -1);
	}
	
	/**
	 * setDate, called when creating fragment with arguments
	 * 
	 * @param string date
	 * 
	 */
	
	
	public void setDate(String date)
	{
		try{
			c.setTime(df.parse(date));
		}catch(Exception e)
		{}
	}
}

